package com.leetcode.code;

import java.util.concurrent.CountDownLatch;

/**
 * Description:
 *
 * @author zkingcobra
 * Date: 2020/6/9 11:13 上午
 */
public class LeetCode1114Java {

    /**
     * 方法一：使用CountDownLatch
     */
    static class Solution {

        private final CountDownLatch c2;
        private final CountDownLatch c3;

        public Solution() {
            c2 = new CountDownLatch(1);
            c3 = new CountDownLatch(1);
        }

        public void first(Runnable printFirst) throws InterruptedException {

            // printFirst.run() outputs "first". Do not change or remove this line.
            printFirst.run();
            c2.countDown();
        }

        public void second(Runnable printSecond) throws InterruptedException {
            c2.await();
            // printSecond.run() outputs "second". Do not change or remove this line.
            printSecond.run();
            c3.countDown();
        }

        public void third(Runnable printThird) throws InterruptedException {
            c3.await();
            // printThird.run() outputs "third". Do not change or remove this line.
            printThird.run();
        }
    }

    /**
     * 用while阻塞线程，并不是好的方法，因为会消耗资源
     */
    static class Solution2 {
        volatile int index = 0;

        public Solution2() {

        }

        public void first(Runnable printFirst) throws InterruptedException {
            // printFirst.run() outputs "first". Do not change or remove this line.
            printFirst.run();
            index++;
        }

        public void second(Runnable printSecond) throws InterruptedException {
            // printSecond.run() outputs "second". Do not change or remove this line.
            while (index != 2) {
            }
            printSecond.run();
            index++;
        }

        public void third(Runnable printThird) throws InterruptedException {

            // printThird.run() outputs "third". Do not change or remove this line.
            while (index != 3) {
            }
            printThird.run();
            index++;
        }
    }
}
